'use strict';
class LocalStorageManager {

  static removeCachedCity() {
    try {
      let _account = null;
      this.getLoginedAccount().then(account => {
        _account = account;
      }, error => {
        throw new Error(error);
      });
      window.localStorage.removeItem('account');
      return _account;
    } catch (error) {
      // Error saving dat
      console.log('LocalStorageManager - set error: ' + error);
      return error;
    }
  }

  static getCachedCity() {
    try {
      const value = window.localStorage.getItem('city');
      return JSON.parse(value);
    } catch (error) {
      // Error retrieving data
      console.log('LocalStorageManager - hasCityCache error: ' + error);
      return error;
    }
  }

  static setHistoryCity(city) {
    try {
      let historyCityList = this.getHistoryCity();
      if (!historyCityList) {
        historyCityList = [];
      }
      historyCityList = historyCityList.filter(_city => {
        return _city.name !== city.name;
      });
      historyCityList.unshift({
        ...city
      });
      if (historyCityList.length > 3) {
        historyCityList = historyCityList.slice(0, 3);
      }
      this.setItem('HistoryCityList', JSON.stringify(historyCityList));
    } catch (e) {
     console.log('ERROR: setHistoryCity' + e.message);
    }
  }

  static getHistoryCity() {
    try {
      let historyCityListJson = this.getItem('HistoryCityList');
      let historyCityList = JSON.parse(historyCityListJson);
      return historyCityList || [];
    } catch (e) {
      console.log('ERROR: setHistoryCity' + e.message);
      return []
    }
  }

  static setItem(key, value, complete) {
    let _error = null;
    try {
      window.localStorage.setItem(key, value);
    } catch (error) {
      // Error saving data
      console.log('LocalStorageManager - set error: ' + error);
      _error = error;
    }
    if (complete) {
      complete(_error);
    }
  }

  static getItem(key, complete) {
    let _value = null;
    let _error = null;
    try {
      _value = window.localStorage.getItem(key);
    } catch (error) {
      // Error retrieving data
      console.log('LocalStorageManager - get error: ' + error);
      _error = error;
    }
    if (complete) {
      complete(_error, _value);
    }
    return _value;
  }

  // static hasLoginCache(complete)
  // {
  //     try {
  //         const value = AsyncStorage.getItem('account');
  //         if (value !== null) {
  //             // We have data!!
  //             complete(true);
  //         } else {
  //             complete(false);
  //         }
  //     } catch (error) {
  //         // Error retrieving data
  //         console.log('LocalStorageManager - hasLoginCache error: ' + error);
  //         complete(false);
  //     }
  // }
}

export
default
LocalStorageManager;
